<?php

namespace App\Http\Controller;

use App\Foundation\OssAssistant;
use App\Foundation\Rbac\UserRBAC;
use App\Http\Entities\AdministratorEntity;
use clagiordano\weblibs\configmanager\ConfigManager;
use Framework\Facade\ConfigFacade;
use Framework\Facade\Facade;
use Framework\Facade\Ini;
use Framework\Foundation\Config;
use Framework\Foundation\Container\Container;

use Framework\Foundation\Database\FDB;
use Framework\Foundation\Entity\EntityBuilder;
use Framework\Foundation\Log\Log;
use Framework\Foundation\Log\LoggerHelper;
use Framework\Foundation\Response\ResponseGen;
use Framework\Foundation\Warehouse;
use Intervention\Image\ImageManager;
use Intervention\Image\ImageManagerStatic;
use Intervention\Image\Imagick\Font;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Firebase\JWT\JWT as ijwt;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Db;
use GuzzleHttp\Cookie\SetCookie;

use Framework\Utils\RedisFactory;
use Naroga\RedisCache\Redis;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use youwen\exwechat\ApiClient;
use youwen\exwechat\Request\Ips;
use youwen\exwechat\Request\WebOAuthToken;
use youwen\exwechat\TokenManager;

class TestController
{
    public function index($request)
    {
        $bannerImage = "http://lib.exwechat.com/dist/images/secret/night/mobilePhone.jpg";
        $name = OssAssistant::extractObjectNameFromUrl($bannerImage);

        $ret = OssAssistant::getObject($name);
//        echo '<pre>';
//        print_r( $ret );
//        exit('</pre>');
//        $ret = file_get_contents($bannerImage);


        $manager = new ImageManager();

        $image = $manager->make($ret);
//        $image = $manager->make(ROOT . '/public' . $bannerImage);
//        header('Content-type:image/jpeg');
        $ret = $image->response('jpg', 90);
        ResponseGen::display($ret);
        exit;
//        exit;
//        echo '<pre>';
//        print_r( $ret );
//        exit('</pre>');
    }

    public function wx()
    {
        $redis = RedisFactory::create();
//        $redis->set('aaab', "123");
//        $ret = $redis->get('aaab');


        $redisCache = new Redis($redis);
        $config = Config::instance()->get('app.wechat');

        $tokenManager = new TokenManager($config, $redisCache);
        $token = $tokenManager->getAccessToken();
        $api = new ApiClient();


//        $ipRequest = (new Ips)->getIps($token);
        $code = WebOAuthToken::getScopeCodeUrl(
            $tokenManager->getConfig()->getAppId(),
            $tokenManager->getConfig()->getRedirectUri()
        );

        $userInfo = WebOAuthToken::getScopeCodeUrl(
            $tokenManager->getConfig()->getAppId(),
            $tokenManager->getConfig()->getRedirectUri(),
            WebOAuthToken::USER_INFO_SCOPE
        );
//        $ret = $api->send($code);


        echo '<pre>';
        print_r($token);
        echo '<br/>';
        echo '<a href="' . $code . '">', "授权", '</a>';
        echo '<br/>';
        echo '<br/>';
        echo '<a href="' . $userInfo . '">', "授权-userinfo", '</a>';
        exit('</pre>');
//        $host = '';
//        $response = ResponseGen::getDefaultResponse();
//        $cookie = new SetCookie(['Name' => 'Authorization', 'Value' => "123", 'Expires' => time() + 86400 * 30]);
//        $response = $response->withHeader('Set-Cookie', $cookie->__toString());
//        $response->withHeader('Location', $host);
    }

    public function callback($request)
    {
        echo '<pre>';
        print_r('yes');
        exit('</pre>');
    }

    public function thinkDb()
    {
        Db::startTrans();
        Db::table('member')->where('member_id', 11)->update(['status' => Db::raw('`status`+1')]);
        $ret = Db::table('member')->limit(2, 2)->select()->first();
        $log = Db::getDbLog();
        Db::commit();

        Db::startTrans();
        Db::table('member')->where('member_id', 20)->update(['status' => Db::raw('`status`+20')]);
        Db::commit();

        echo '<pre>';
        print_r($ret);
        print_r($log);
        print_r(Db::getLastSql());
        echo '<br/>', '--------------', '<br/>';
        print_r(Db::getError());
        exit('</pre>');
    }

    /**
     * XML转数组
     * @author baiyouwen
     */
    public static function xmlToArray($xml)
    {
        $data = [];
        $postObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = self::_xml2arr($postObj);
        return $data;
    }

    private static function _xml2arr($obj, $l = 1)
    {
        $arr = array();
        foreach ($obj as $key => $value) {
            if (isset($arr[$key])) {
                if (isset($arr[$key][0])) {
                    if ($value->children()) {
                        $arr[$key][] = self::_xml2arr($value, $l++);
                    } else {
                        $arr[$key][] = strval($value);
                    }
                } else {
                    $arr[$key] = array($arr[$key]);
                    if ($value->children()) {
                        $arr[$key][] = self::_xml2arr($value, $l++);
                    } else {
                        $arr[$key][] = strval($value);
                    }
                }
            } else {
                if ($value->children()) {
                    $arr[$key] = self::_xml2arr($value, $l++);
                } else {
                    $arr[$key] = strval($value);
                }
            }
        }
        return $arr;
    }


    public function index_1($request)
    {
        $parentId = 100000;
        $provinceList = FDB::from('region')
            ->where('parent_id=?', $parentId)
            ->fetchAll();
//        echo '<pre>';
//        print_r( $list );
//        exit('</pre>');

        $level0 = $this->listToString($provinceList);
        echo 'dsy.add("0", [' . $level0 . '])', '<br/>';

        $i = 0;
        foreach ($provinceList as $province) {
            $cityList = FDB::from('region')
                ->where('parent_id=?', $province['id'])
                ->fetchAll();
            $level1 = $this->listToString($cityList);
            echo 'dsy.add("0_' . $i . '", [' . $level1 . '])', '<br/>';

            $j = 0;
            foreach ($cityList as $city) {
                $areaList = FDB::from('region')
                    ->where('parent_id=?', $city['id'])
                    ->fetchAll();
                $level2 = $this->listToString($areaList);
                echo "dsy.add(\"0_{$i}_{$j}\", [" . $level2 . "])", '<br/>';
                $j++;
            }

            $i++;
        }
        exit;

//        $response = ResponseGen::success();
//        $response = $response->withHeader('Location', 'http://codeper.com/');
//
//        return $response;
//        $entity = EntityBuilder::GenByPkId('order_base', 1);
//        $no = $entity->orderNo();
//        echo '<pre>';
//        var_dump($entity);
//        var_dump($no);
//        exit('</pre>');
    }

    public function listToString($array)
    {
        $string = '';
        foreach ($array as $province) {
            $string .= "\"" . $province['name'] . "\", ";
        }

        return rtrim($string, ', ');
    }
}
